# @Time : 2021/10/25 20:52
# @Author : Li Kunlun
# @Description : 使用进程池在web服务中实现加速

import flask
import json
import time
from concurrent.futures import ProcessPoolExecutor
import math
import json

app = flask.Flask(__name__)


# 判断是否为素数(cpu计算，没有涉及io)
def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True


# numbers表示一个参数
@app.route("/is_prime/<numbers>")
def api_is_prime(numbers):
    number_list = [int(x) for x in numbers.split(",")]
    results = process_pool.map(is_prime, number_list)
    # 将两个列表合并成一个字典 dict(zip())方法
    # https://blog.csdn.net/zongza/article/details/88075156
    return json.dumps(dict(zip(number_list, results)))


if __name__ == '__main__':
    # 初始化全局进程池-放到这个位置才能够正常使用
    process_pool = ProcessPoolExecutor()
    app.run()
